package me.shurufa.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.File;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.activities.PhotoPickerActivity;
import me.shurufa.activities.SelectDigestBookActivity;
import me.shurufa.bean.Catalog;
import me.shurufa.bean.Excerpt;
import me.shurufa.model.AddDigestBean;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.CatalogListResp;
import me.shurufa.response.UploadImageResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.popupwindow.WheelPopWindow;
import me.shurufa.widget.smoothcamera.Photo;
import me.shurufa.widget.smoothcamera.core.CameraManager;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 内容简介 Fragment
 */
public class ModifyMyDigestFragment extends BaseFragment implements View.OnClickListener {

    private static final int PICK_PHOTO = 0x12;

    @Bind(R.id.btn_select_chapter)
    TextView mSelectChapterBtn;

    @Bind(R.id.et_page_num)
    EditText et_page_num;

    @Bind(R.id.et_note)
    EditText et_note;

    @Bind(R.id.et_digest)
    EditText et_digest;

    @Bind(R.id.iv_digest)
    ImageView iv_digest;

    @Bind(R.id.cb_save_not_send)
    CheckBox cb_save_not_send;

    @Bind(R.id.tv_save_send)
    TextView tv_save_send;

    @Bind(R.id.iv_edit)
    ImageView iv_edit;

    @Bind(R.id.ll_checkbox)
    LinearLayout ll_checkbox;

    private Dialog mDialog;
    private Excerpt mExcerpt;
    private String mBookName;
    private long mBookId;
    private long mNoteBookId;
    private AddDigestBean mTemp;
    private List<Catalog> mCatalogs;

    private KProgressHUD kProgressHUD;
    private ReferenceQueue<Bitmap> rq = new ReferenceQueue<>();
    private WeakReference<Bitmap> mCropBitmap;

    public static ModifyMyDigestFragment newInstance(String bookName, long bookId, Excerpt digest) {
        ModifyMyDigestFragment fragment = new ModifyMyDigestFragment();
        Bundle args = new Bundle();
        args.putSerializable(Constants.ARG_ADD_DIGEST, digest);
        args.putSerializable(Constants.ARG_BOOK, bookName);
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mExcerpt = (Excerpt) getArguments().getSerializable(Constants.ARG_ADD_DIGEST);
            mBookName = getArguments().getString(Constants.ARG_BOOK);
            mBookId = getArguments().getLong(Constants.ARG_BOOK_ID, 0l);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_modify_digest, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

        if (mCropBitmap != null) {
            mCropBitmap.clear();
            mCropBitmap = null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == me.shurufa.widget.smoothcamera.Constants.REQUEST_CROP && resultCode == Activity.RESULT_OK) {
            //data.getData().getPath() 上传图片
            uploadImg(data.getData().getPath());
        }

        //相册选择完成后，返回图片路径 打开剪裁页面
        if (requestCode == PICK_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                ArrayList<String> resultData = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                if (resultData != null && resultData.size() > 0) {
                    String path = resultData.get(0);

                    if (TextUtils.isEmpty(path)) {
                        Utils.showToast("选取图片出错啦，请再试试");
                        return;
                    }

                    CameraManager.getInstance().processPhotoItem(getActivity(),
                            new Photo(path, System.currentTimeMillis()), null, Constants.TYPE_FROM_MODIFY_IMAGE_DIGEST);
                }
            }
        }

    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.EVENT_CHANGE_IMAGE_DIGEST.equals(intent.getAction())) {
            if (intent.getData() != null) {
                uploadImg(intent.getData().getPath());
            }
        }
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        ll_checkbox.setVisibility(Constants.SAVE.equals(mExcerpt.publish_state) ? View.VISIBLE : View.GONE);
        cb_save_not_send.setChecked(Constants.SAVE.equals(mExcerpt.publish_state));
        initData();
        initListener();
    }

    private void initListener() {
        mSelectChapterBtn.setOnClickListener(this);
        tv_save_send.setOnClickListener(this);
        iv_edit.setOnClickListener(this);
    }

    private void initData() {
        showDigestContent();

        // 显示页码
        et_page_num.setText(mExcerpt.page_num == 0 ? null : String.valueOf(mExcerpt.page_num));
        // 显示当前章节的名称

        // 章节id 章节名
        if (!TextUtils.isEmpty(mExcerpt.menu_title)) {
            mSelectChapterBtn.setText(mExcerpt.menu_title);
        }
    }

    private void showDigestContent() {
        if (Constants.DIGEST_TYPE_TEXT == mExcerpt.type) {
            iv_digest.setVisibility(View.GONE);
            iv_edit.setVisibility(View.GONE);
            et_digest.setVisibility(View.VISIBLE);
            et_digest.setText(mExcerpt.content);
            et_digest.requestFocus();
        } else {
            et_digest.setVisibility(View.GONE);
            iv_digest.setVisibility(View.VISIBLE);
            iv_edit.setVisibility(View.VISIBLE);
            // 图片书摘
            // Glide.with(getActivity()).load(mDigest.getScreenshot() + Constants.THUMB_SUFFIX).centerCrop()
            //         .placeholder(R.drawable.ic_placeholder_digest_image).error(R.drawable.ic_placeholder_digest_image).into(iv_digest);

            Glide.with(this).load(mExcerpt.screenshot)//  + Constants.THUMB_SUFFIX)
                    .asBitmap()
                    .centerCrop()
                    .placeholder(R.drawable.ic_placeholder_digest_image)
                    .error(R.drawable.ic_placeholder_digest_image)
                    .into(new BitmapImageViewTarget(iv_digest) {
                @Override
                protected void setResource(Bitmap resource) {
                    mCropBitmap = new WeakReference<Bitmap>(resource, rq);
                    iv_digest.setImageBitmap(resource);
                }
            });
        }

        if (!TextUtils.isEmpty(mExcerpt.note)) {
            et_note.setText(mExcerpt.note);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select_digestbook:

                if (null == mTemp) {
                    mTemp = new AddDigestBean();
                }

                Intent in = new Intent(getActivity(), SelectDigestBookActivity.class);
                SelectDigestBookActivity.initArguments(in, mTemp);
                startActivity(in);
                break;
            case R.id.tv_save_send:
                cb_save_not_send.toggle();
                break;
            case R.id.btn_select_chapter:
                if (!Utils.isNullForList(mCatalogs)) {
                    showSelectCatalogWheelView();
                } else {
                    reqCatalogs();
                }
                break;
            case R.id.iv_edit:
                showDialog();
                break;


            // 弹出菜单
            case R.id.take_photo:
                mDialog.dismiss();
                CameraManager.getInstance().openCamera(getActivity(), Constants.TYPE_FROM_MODIFY_IMAGE_DIGEST);
                break;
            case R.id.take_gally:
                mDialog.dismiss();
                Intent intent = new Intent(getActivity(), PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            case R.id.cancel:
                mDialog.dismiss();
                break;
            case R.id.cut_image:
                mDialog.dismiss();

                if (mCropBitmap != null) {
                    syncCutImage();
                } else {
                    Utils.showToast("图片未加载完成");
                }
                break;

        }
    }

    private void syncCutImage() {
        kProgressHUD = KProgressHUD.create(getActivity());
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(getString(R.string.commit_pls_wait))
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 存储到本地 获得本地路径
                try {
                    if (mCropBitmap == null || mCropBitmap.get() == null) {
                        Utils.showToast("获取图片失败, 请尝试其他替换图片书摘的方式!");
                        return;
                    }

                    final String savePath = Utils.saveFileToGetPath(getActivity(), mCropBitmap.get());

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(savePath)) {
                                Utils.showToast("获取图片失败, 请尝试其他替换图片书摘的方式!");
                                return;
                            }
                            if (kProgressHUD != null) {
                                kProgressHUD.dismiss();
                                kProgressHUD = null;
                            }
                            CameraManager.getInstance().processPhotoItem(getActivity(),
                                    new Photo(savePath, System.currentTimeMillis()), null, Constants.TYPE_FROM_MODIFY_IMAGE_DIGEST);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    Utils.showToast("获取图片失败, 请尝试其他替换图片书摘的方式!");
                }
            }
        }).start();


    }

    /**
     * 打开滚轮控件 选择章节
     */
    private void showSelectCatalogWheelView() {
        final WheelPopWindow wheelPopWindow = new WheelPopWindow(getActivity(), mCatalogs);
        wheelPopWindow.showPickerWindow(mSelectChapterBtn, 0);
        wheelPopWindow.setOnCompleteClickListener(new WheelPopWindow.OnCompleteClickListener() {
            @Override
            public void onCompleteClicked() {
                Catalog selectedCatalog = wheelPopWindow.getCurrentData();
                mSelectChapterBtn.setText(selectedCatalog.title);
                mExcerpt.menu_id = Integer.parseInt(selectedCatalog.id);
                mExcerpt.menu_title = selectedCatalog.title;
                wheelPopWindow.dismiss();
            }

            @Override
            public void onItemSelected() {
                Catalog selectedCatalog = wheelPopWindow.getCurrentData();
                mSelectChapterBtn.setText(selectedCatalog.title);
                mExcerpt.menu_id = Integer.parseInt(selectedCatalog.id);
                mExcerpt.menu_title = selectedCatalog.title;
            }
        });
    }

    private void reqCatalogs() {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", mBookId);
        HttpRequest.post(API.GET_BOOK_MENU, params, new HttpCallback<CatalogListResp>(getActivity(), getString(R.string.list_footer_loading)) {
            @Override
            public void onRespSuccess(CatalogListResp resp) {
                try {
                    if (Utils.isNullForList(resp.data)) {
                        Utils.showToast(getString(R.string.no_chapter));
                    } else {
                        mCatalogs = resp.data;
                        showSelectCatalogWheelView();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(CatalogListResp resp) {

            }
        });

    }


    /**
     * 选择书摘本
     */
    /*public void onEventMainThread(Intent intent) {
        if (intent.getAction().equals(Constants.EVENT_SELECT_DIGEST_BOOK)){
            mTemp = (AddDigestBean) intent.getSerializableExtra(Constants.EVENT_SELECT_DIGEST_BOOK);
            mSelectDigestBookBtn.setText(mTemp.excerptedBookTitle);
        }
    }*/

    /**
     * 获得书摘
     * @return 书摘
     */
    public Excerpt getExcerpt() {
        mExcerpt.content = (et_digest.getText().toString().trim());
        mExcerpt.note = (et_note.getText().toString().trim());
        mExcerpt.publish_state = (cb_save_not_send.isChecked() ? Constants.SAVE : Constants.PUBLISH);
        try {
            mExcerpt.page_num = Integer.parseInt(et_page_num.getText().toString());
        } catch (Exception e) {
            mExcerpt.page_num = 0;
        }
        if (null != mTemp) {
            //mDigest.setNotebook_id(mTemp.excerptedBookId + "");
            mNoteBookId = mTemp.excerptedBookId;
        }

        // 关闭键盘
        Utils.closeInputMethod(getActivity(), et_digest);
        return mExcerpt;
    }

    /**
     * 获得书摘本ID 但是要在getDigest() 方法后才可以进行调用
     * @return
     */
    public long getNoteBookId() {
        return mNoteBookId;
    }

    private void showDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_choose_digest_image, null);
        Button takePhoto = (Button) view.findViewById(R.id.take_photo);
        Button takeGally = (Button) view.findViewById(R.id.take_gally);
        Button cancel = (Button) view.findViewById(R.id.cancel);
        Button cutImage = (Button) view.findViewById(R.id.cut_image);

        cutImage.setOnClickListener(this);
        takePhoto.setOnClickListener(this);
        takeGally.setOnClickListener(this);
        cancel.setOnClickListener(this);

        mDialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle);
        mDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = mDialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        mDialog.onWindowAttributesChanged(wl);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.show();

    }

    private void uploadImg(String path) {
        File file = new File(path);
        RequestParams params = new RequestParams();
        params.addFormDataPart("image", file);
        HttpRequest.post(API.UPLOAD_IMAGE, params, new HttpCallback<UploadImageResp>(getActivity(), getString(R.string.submit_loading)) {

            @Override
            public void onRespSuccess(UploadImageResp uploadImageResp) {
                try {
                    if (!TextUtils.isEmpty(uploadImageResp.data.url)) {
                        mExcerpt.screenshot = (uploadImageResp.data.url);
                        // 图片书摘
                        Glide.with(getActivity()).load(mExcerpt.screenshot + Constants.THUMB_SUFFIX).crossFade().centerCrop()
                                .placeholder(R.drawable.ic_placeholder_digest_image).error(R.drawable.ic_placeholder_digest_image).into(iv_digest);
                    }
                } catch (Exception e) {
                    Utils.showToast(R.string.sys_err);
                }
            }

            @Override
            public void onRespFailure(UploadImageResp uploadImageResp) {

            }
        });
    }
}
